<?php
namespace Admin\Model;
use Think\Model;
class TagModel extends Model{
	//获取标签分类
	public function get_type($pid=0){
		$type=M('tag_type');
		return $type->where(array('pid'=>$pid))->select();
	}
	
	//添加标签[手动]
	public function addtag($pid,$sonid,$content){
		$content=trim($content,',');
		$arr=explode(',', $content);
		foreach ($arr as $v){
			//如果新增的标签未存在，则添加新标签
			if ($this->check_tag($v,$pid,$sonid)==0) {
					$data[]=array(
						'name'=>$v,
						'pid'=>$pid,
						'sonid'=>$sonid,
						'click'=>rand(100, 500),	
					);
			}
		}
		if(is_array($data)){
			$this->addAll($data);
			return mysql_affected_rows() >0 ? 1:0;
		}else{
			return 0;
		}
	}
	
	//采集百度风云榜自动添加标签
	public function baidutag($pid,$sonid,$url){
		$arr=$this->preg_keyword($url);
		foreach ($arr as $v){
			if ($this->check_tag($v,$pid,$sonid)==0) {
				$data[]=array(
					'name'=>$v,
					'click'=>rand(100, 500),
					'pid'=>$pid,
					'sonid'=>$sonid	
				);
			}
		}
		if(is_array($data)){
			$this->addAll($data);
			return mysql_affected_rows() >0 ? 1:0;
		}else{
			return 0;
		}
		
	}
	
	
	
	//检查标签是否存在
	public function check_tag($tagname,$pid,$sonid){
		$data=$this->where(array('name'=>$tagname,'pid'=>$pid,'sonid'=>$sonid))->find();
		return is_array($data) ? 1:0; 
	}
	
	//匹配百度风云榜关键字
	public function preg_keyword($url){
		$content=file_get_contents($url);
		$content=iconv('gb2312', 'utf-8', $content);
		$content=html_entity_decode($content);
		$pattern="#<a class=\"list\-title\" (.*)>(.*)\<\/a\>#isU";
		preg_match_all($pattern, $content,$arr);
		return $arr[2];
// 		print_r($arr[2]);die();
	}
	
	//获取标签
	public function get_tag($page=1,$listRows=20){
		return $this->page($page.','.$listRows)->order('id desc')->select();
	}
	
	
	
	
	
	
	
	
}